package me.ywy.ximalaya;

import java.io.File;

import net.sf.json.JSONObject;

public class Sound {
	private String id;
	private String downUrl_64;
	private String downUrl_32;
	private String albumId;
	private String name;
	private String index;

	public Sound(String id, String albumId, String index) {
		this.id = id;
		this.albumId = albumId;
		this.index = index;
	}

	public String getId() {
		return id;
	}

	public boolean init() {
		String url = Config.SOUND_JSON_URL + id + ".json";
		String json = Tools.getHttpData(url);
		JSONObject sound = JSONObject.fromObject(json);
		if (sound.optString("title").isEmpty() || sound.optString("play_path_64").isEmpty()) {
			return false;
		}
		downUrl_64 = sound.optString("play_path_64");
		downUrl_32 = sound.optString("play_path_32");
		String ext = downUrl_64.substring(downUrl_64.lastIndexOf("."), downUrl_64.length());
		if (index != null) {
			name = index + "-" + sound.optString("title") + ext;
		} else {
			name = sound.optString("title") + ext;
		}
		name = name.replace("\\", "").replace("/", "");
		System.out.println(name + ":" + downUrl_64);
		downUrl_64 = Config.SOUND_DOWN_URL + downUrl_64;
		downUrl_32 = Config.SOUND_DOWN_URL + downUrl_32;
		return true;
	}

	public void download(boolean hq) {
		File f = new File(Config.FILE_SAVE_PATH);
		if (!f.exists()) {
			f.mkdir();
		}
		System.out.println("Down " + name);
		String downUrl = hq ? downUrl_64 : downUrl_32;
		if (albumId != null) {
			f = new File(Config.FILE_SAVE_PATH + File.separator + albumId);
			if (!f.exists()) {
				f.mkdir();
			}
			Tools.downloadFile(downUrl, Config.FILE_SAVE_PATH + File.separator + albumId + File.separator + name);
		} else {
			Tools.downloadFile(downUrl, Config.FILE_SAVE_PATH + File.separator + name);
		}
	}
}
